<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="标题" prop="biaoti">
        <el-input
          v-model="queryParams.biaoti"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <!-- <el-form-item label="发布人" prop="faburen">
        <el-input
          v-model="queryParams.faburen"
          placeholder="请输入发布人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="文章分类" style="width: 250px;" prop="categoryId">
        <el-select clearable  v-model="queryParams.categoryId" placeholder="请选择文章分类"  >
                    <el-option v-for="item in categoriesList" :key="item.categoryId" :label="item.name" :value="item.categoryId" />
                </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:news:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:news:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:news:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:news:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="newsId" />
      <el-table-column label="创建时间" align="center" prop="addtime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.addtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="biaoti" />
      <!-- <el-table-column label="内容" align="center" prop="neirong" /> -->
      <el-table-column label="视频" align="center" prop="shipin" />
      <el-table-column label="发布时间" align="center" prop="fabushijian" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.fabushijian, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="faburen" />
      <el-table-column label="封面" align="center" prop="fengmian" width="230" >
        <template #default="scope">
          <el-image style="width: 115px; height: 80px" :src="scope.row.fengmian" :preview-src-list="[scope.row.fengmian]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="赞" align="center" prop="thumbsupnum" />
      <el-table-column label="踩" align="center" prop="crazilynum" />
      <el-table-column label="最近点击时间" align="center" prop="clicktime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.clicktime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点击次数" align="center" prop="clicknum" />
      <el-table-column label="文章分类id" align="center" prop="categoryId" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" >
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:categories:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" >
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:categories:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" v-if="open" v-model="open" width="1200px" append-to-body center>
      <el-form ref="newsform" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="biaoti">
          <el-input v-model="form.biaoti" placeholder="请输入标题" />
        </el-form-item>
        <!-- <el-form-item label="上传视频" prop="shipin">
            <el-upload
                action="#"
                :http-request="requestUploadVideo"
                v-model="form.shipin"
                :show-file-list="true"
                :before-upload="beforeUploadVideo"
              >
            <el-button>
              选择视频
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="发布时间" prop="fabushijian">
          <el-date-picker
          v-model="form.fabushijian"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="发布时间">
        </el-date-picker>
        </el-form-item>
        <el-form-item label="发布人" prop="faburen">
          <el-input v-model="form.faburen" placeholder="请输入发布人" />
        </el-form-item>
        <el-form-item label="封面" prop="fengmian">
            <fengmianImg :fengmian="form.fengmian"  @event="getChildFengmian" v-model="form.fengmian" />
        </el-form-item>
        <el-form-item label="请选择文章分类" prop="categoryId">
          <el-select clearable v-model="form.categoryId" placeholder="请选择文章分类"  >
                    <el-option v-for="item in categoriesList" :key="item.categoryId" :label="item.name" :value="item.categoryId" />
                </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="neirong">
          <!-- <myTinymce style="z-index: 1000;" ref="myTinymce" v-model="form.neirong" :height="400"></myTinymce> -->
          <editor v-model="form.neirong" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确定
        </el-button>
      </div>
    </template>
    </el-dialog>

  </div>
</template>

<script setup name="newsManagement">
import { listNews, getNews, delNews, addNews, updateNews } from "@/api/system/news";
import Cookies from "js-cookie";

import myTinymce from "@/components/myTinymce/index";
import { uploadVideo } from "@/api/system/user";
import { listCategories } from "@/api/system/categories";
import fengmianImg from "./fengmianImg";
import useUserStore from "@/store/modules/user";
import { onMounted } from "vue";
const userStore = useUserStore();

const { proxy } = getCurrentInstance();

const loading = ref(true);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const newsList = ref([]);
const title = ref("");
const open = ref(false);
const ids = ref([]);
const content = ref("<p>请输入内容</p>");
const categoriesList = ref([]);
const dataOptions = reactive({
  queryParams: {
        pageNum: 1,
        pageSize: 10,
        addtime: null,
        biaoti: null,
        neirong: null,
        shipin: null,
        fabushijian: null,
        faburen: null,
        fengmian: null,
        thumbsupnum: null,
        crazilynum: null,
        clicktime: null,
        clicknum: null,
        categoryId: null
  },
  vidoeFile: {
      data: null,
      filename: ''
  },
  form: {fabushijian: '',neirong: ''},
  rules: {
    addtime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
  }   
});

const { queryParams, vidoeFile, form, rules } = toRefs(dataOptions);
      

onMounted (()=>{
  getList();
  getCategoriesList();
})


       /** 查询新闻列表 */
  const getList = () => {
      loading.value = true;
      listNews(queryParams.value).then(response => {
        newsList.value = response.rows;
        total.value = response.total;
        loading.value = false;
      });
    }
    // 取消按钮
  const cancel = () => {
      open.value = false;
      reset();
    }
    // 表单重置
  const reset = () => {
      form.value = {
        newsId: null,
        addtime: null,
        biaoti: null,
        neirong: null,
        shipin: null,
        fabushijian: null,
        faburen: null,
        fengmian: null,
        thumbsupnum: null,
        crazilynum: null,
        clicktime: null,
        clicknum: null,
        categoryId: null
      };
      proxy.resetForm("form");
    }
    /** 搜索按钮操作 */
  const  handleQuery = ()=> {
      queryParams.value.pageNum = 1;
      getList();
    }
    /** 重置按钮操作 */
  const resetQuery = ()=> {
    proxy.resetForm("queryForm");
      handleQuery();
    }
    // 多选框选中数据
  const  handleSelectionChange = (selection)  =>{
      ids.value = selection.map(item => item.newsId)
      single.value = selection.length!==1
      multiple.value = !selection.length
    }
    /** 新增按钮操作 */
   const handleAdd = ()=> {
      reset();
      form.value.faburen = Cookies.get("username");
      open.value = true;
      title.value = "添加新闻";
    }
    /** 修改按钮操作 */
   const handleUpdate = (row)=> {
      reset();
      const newsId = row.newsId || ids.value
      getNews(newsId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改新闻";
      });
    }
    /** 提交按钮 */
   const submitForm = ()=> {
      proxy.$refs["newsform"].validate(valid => {
        if (valid) {
          if(form.value.shipin != null && form.value.shipin != '') {
            subUploadVideo();
          }
          const requestForm = JSON.parse(JSON.stringify(form.value));
          
          console.log(requestForm,"this.form");
          if (form.value.newsId != null) {
            updateNews(requestForm).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
          } else {
            addNews(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
          }
        }
      });
    }

    /** 删除按钮操作 */
   const handleDelete = (row) => {
      let arr = row.newsId || ids.value;
      if(typeof arr == "number" ) {
        arr = [arr]
      }
      proxy.$modal.confirm('是否确认删除新闻编号为"' + arr + '"的数据项？').then(function() {
        return delNews([...arr]);
      }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
    /** 导出按钮操作 */
   const handleExport = ()=> {
      this.download('system/news/export', {
        ...queryParams.value
      }, `news_${new Date().getTime()}.xlsx`)
    }
   const handleRemove = (file, uploadFiles)=> {
      console.log(file, uploadFiles)
    }

  const handlePreview = (uploadFile) => {
    console.log(uploadFile)
  }

    handleExceed: (files, uploadFiles) =>{
      ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${
          files.length + uploadFiles.length
        } totally`
      )
    }

    const beforeRemove = (uploadFile, uploadFiles)=>  {
      return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
      ).then(
        () => true,
        () => false
      )
    }
    /** 上传视频预处理 */
    const beforeUploadVideo = (file) => {
      if (file.type.indexOf("video/") == -1) {
        proxy.$modal.msgError("文件格式错误，请上传视频类型,如：mp4, avi,rmvb后缀的文件。");
      } else {
        const reader = new FileReader();
        vidoeFile.value.data = file;
        reader.readAsDataURL(file);
        reader.onload = () => {
          vidoeFile.value.img = reader.result;
          vidoeFile.value.filename = file.name;
        };
      }
    }
  //默认的上传
  const requestUploadVideo = ()=> { }
  //实际的上传视频
  const subUploadVideo = () =>{
    let formData = new FormData();
    formData.append("videofile", vidoeFile.value.data, vidoeFile.value.filename);
    uploadVideo(formData).then(response => {
      form.value.shipin = import.meta.env.VITE_APP_BASE_API + response.videoUrl;
      proxy.$modal.msgSuccess("视频上传成功！");
    });
  }
  //分类列表
 const getCategoriesList = () => {
    let queryParams = {
        pageNum: 1,
        pageSize: 100,
        name: null,
        createdAt: null,
        updatedAt: null
      };
    listCategories(queryParams).then(response => {
        categoriesList.value = response.rows;
      });
  }

  const getChildFengmian = (val) => {
    console.log(val,"val");
    form.value.fengmian = val;
  }

</script>
<style >
/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux{z-index:99999 !important;}
.tinymce.ui.FloatPanel{z-Index: 99;}
</style>